const express = require('express');
const app = express();
const axios = require('axios');

// 换取 openid 和 session_key
async function getOpenid(code) {
  const appid = 'wxa5dfbc1b3ddb208e';
  const secret = 'ee210188f0564bd0389b297f4077176a';
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;

  try {
    const response = await axios.get(url);
    const { openid, session_key } = response.data;
    return openid;
  } catch (error) {
    console.error('换取 openid 失败', error);
    return null;
  }
}

app.get('/', (req, res) => {
  res.send('Hello World!');
});

// 定义 /getOpenId 路由
app.get('/getOpenId', async (req, res) => {
  const code = req.query.code; // 获取查询参数 code
  if (!code) {
    return res.status(400).json({ error: 'Missing code parameter' });
  }

  // 模拟获取 openid 的逻辑
  const openid = await getOpenid(code);

  // 返回 openid
  res.json({ openid });
});

app.listen(80, () => {
  console.log('Server is running on http://localhost:80');
});